package com.sunky.rfidapp.util

import android.widget.Toast
import com.nativec.tools.ModuleManager
import com.nativec.tools.SerialPortFinder
import com.rfid.RFIDReaderHelper
import com.rfid.ReaderConnector
import com.sunky.rfidapp.RFID_Application
import java.security.InvalidParameterException
import java.util.*

class RFIDUtils {
    companion object {
        private val connector = ReaderConnector()

        private val mSerialPortFinder = SerialPortFinder()

//        private val mReaderHelper = RFIDReaderHelper.getDefaultHelper()

        fun connect(): Boolean {
            val devNames = mSerialPortFinder.allDevices
            val devPaths = mSerialPortFinder.allDevicesPath
            var address: String? = null
            devNames.indices.forEach {
                if (devNames[it] == "ttyS4 (rk_serial)") {
                    address = devPaths[it]
                    return@forEach
                }
            }
            try {
                if (connector.connectCom(address, 115200)) {
                    try {
                        ModuleManager.newInstance().uhfStatus = true
                    } catch (e: Exception) {
                        e.printStackTrace()
                        return false
                    }
                } else {
                    Toast.makeText(RFID_Application.context, "RFID连接失败", Toast.LENGTH_SHORT).show()
                    return false
                }

                ModuleManager.newInstance().uhfStatus = true
                Toast.makeText(RFID_Application.context, "RFID连接成功", Toast.LENGTH_SHORT).show()
                return true
                //finish();
            } catch (e: SecurityException) {
                Toast.makeText(
                        RFID_Application.context,
                        "串口号没有读写权限",
                        Toast.LENGTH_SHORT).show()
                return false
            } catch (e: InvalidParameterException) {
                Toast.makeText(
                        RFID_Application.context,
                        "请配置",
                        Toast.LENGTH_SHORT).show()
                return false
            }
        }

        fun disconnect() {
            try {
                connector.disConnect()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun registerObserver(observer: Observer){
            try {
                RFIDReaderHelper.getDefaultHelper().registerObserver(observer)
//                RFIDReaderHelper.getDefaultHelper().setBeeperMode(1, 1)
                RFIDReaderHelper.getDefaultHelper().setTrigger(true)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun unregisterObserver(observer: Observer) {
            try {
                RFIDReaderHelper.getDefaultHelper().unRegisterObserver(observer)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}